package com.srwl.mytx.im.core;

import android.util.Log;

import com.srwl.mytx.im.interf.IMSClient;
import com.srwl.mytx.im.protobuf.MessageProtobuf;
import com.srwl.mytx.Constant;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.util.internal.StringUtil;

/**
 * <p>@ProjectName:     NettyChat</p>
 * <p>@ClassName:       MsgSendManager.java</p>
 * <p>@PackageName:     com.freddy.im</p>
 * <b>
 * <p>@Description:     消息发送管理器，用于管理消息定时器的新增、移除等</p>
 * </b>
 * <p>@author:          FreddyChen</p>
 * <p>@date:            2019/04/09 22:42</p>
 * <p>@email:           chenshichao@outlook.com</p>
 */
public class MsgSendManager {
    private static final String TAG = "MsgSendManager";
    private Map<String, MsgTimeoutTimer> mMsgTimeoutMap = new ConcurrentHashMap<>();
    private IMSClient imsClient;// ims客户端

    public MsgSendManager(IMSClient imsClient) {
        this.imsClient = imsClient;
    }

    /**
     * 添加消息到发送管理器
     *
     * @param msg
     */
    public void add(MessageProtobuf.Msg msg) {
        if (msg == null || msg.getHead() == null) {
            return;
        }

        int msgType = msg.getHead().getMsgType();
        // 如果服务端没有发回 “消息收到回执”，客户端需要重发的相对重要的消息，才丢进消息发送管理器
        if (msgType == Constant.C2C_MESSAGE || msgType == Constant.NOTIFY_MESSAGE) {
            String msgId = msg.getHead().getMsgId();
            if (!mMsgTimeoutMap.containsKey(msgId)) {
                MsgTimeoutTimer timer = new MsgTimeoutTimer(imsClient, msg);
                mMsgTimeoutMap.put(msgId, timer);
            }
            Log.d(TAG, "add:添加消息到发送管理器，message=" + msg.getBody() + "当前待处理消息数：" + mMsgTimeoutMap.size());
        }
    }

    /**
     * 从发送超时管理器中移除消息，并停止定时器
     *
     * @param msgId
     */
    public void remove(String msgId) {
        if (StringUtil.isNullOrEmpty(msgId)) {
            return;
        }

        Log.d(TAG, "remove: 从消息管理器清除消息: " + msgId);
        MsgTimeoutTimer timer = mMsgTimeoutMap.remove(msgId);
        if (timer != null) {
            timer.cancel();
        }

    }

    /**
     * 重连成功回调，重连并握手成功时，重发消息发送超时管理器中所有的消息
     */
    public synchronized void onResetConnected() {
        for (Iterator<Map.Entry<String, MsgTimeoutTimer>> it = mMsgTimeoutMap.entrySet().iterator(); it.hasNext(); ) {
            it.next().getValue().sendMsg();
        }
    }
}
